from uiautomator2 import Device
import uiautomator2 as u2
import time
import random
import re


class SearchGoods:
    APP_NAME = 'com.jd.b2b.jdws.rn'
    device = None
    activity = 'com.jd.bmall.search.ui.activity.SearchActivity'

    def __init__(self, id_list):
        try:
            self.id_list = id_list
            self.device = u2.connect('emulator-5554')
        except Exception as e:
            print("未检测到雷电模拟器")

    def search_input(self, code):
        self.device(resourceId='com.jd.b2b.jdws.rn:id/search_layout').click()
        self.device(resourceId='com.jd.b2b.jdws.rn:id/search_layout').send_keys("")
        self.device(resourceId='com.jd.b2b.jdws.rn:id/search_layout').send_keys(code)

    def search_done(self):
        self.device(text='搜索').click()

    def get_page_content(self):
        self.device.dump_hierarchy()

    def click_input(self):
        if self.device(text='请输入佣金商品名称/商品编号').exists:
            self.device(text='请输入佣金商品名称/商品编号').click()

    def business(self, code):
        self.search_input(code=code)
        self.search_done()
        time.sleep(2)
        return self.device.dump_hierarchy()

    def check_app(self):
        try:
            app_info = self.device.app_info(self.APP_NAME)
        except Exception as e:
            print("在模拟器上未找到app")
            return False
        else:
            return True


if __name__ == '__main__':
    id_list = [
        "100015323310",
        "100008607215",
        "100139495322",
        "100102973978",
        "100098379126",
        "100097383478",
        "100094743383",
        "100087299238",
        "100077121255",
        "100075838899",
        "100069479625",
        "100062292817",
        "100057393996",
        "100046501925",
        "100044961079",
        "100037440680",
        "100029814387",
        "100028585878",
        "100027660305",
        "100023309156",
    ]

    sg = SearchGoods(id_list)
    sg.click_input()
    isInstall = sg.check_app()
    if isInstall:
        for id in id_list:
            page_content = sg.business(id)
